package com.zlf.sb.demo.service.impl;

import com.zlf.sb.demo.service.ObjectLogicFunction;
import com.zlf.sb.demo.service.TransactionControlService;
import com.zlf.sb.demo.service.VoidLogicFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

@Service
public class TransactionControlServiceImpl implements TransactionControlService {
    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    /**
     * 事务处理
     *
     * @param businessLogic 业务逻辑
     * @param <T>           result type
     * @return 处理结果
     * @throws Exception 业务异常信息
     */
    @Override
    public <T> T execute(ObjectLogicFunction<T> businessLogic) throws Exception {
        TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            T resp = businessLogic.logic();
            platformTransactionManager.commit(transactionStatus);
            return resp;
        } catch (Exception e) {
            platformTransactionManager.rollback(transactionStatus);
            throw new Exception(e);
        }
    }

    /**
     * 事务处理
     *
     * @param businessLogic 业务逻辑
     */
    @Override
    public void execute(VoidLogicFunction businessLogic) throws Exception {
        TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            businessLogic.logic();
            platformTransactionManager.commit(transactionStatus);
        } catch (Exception e) {
            platformTransactionManager.rollback(transactionStatus);
            throw new Exception(e);
        }
    }
}